package controller;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Set;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.AttributeModel;
import model.SearchForm;

import org.apache.commons.lang3.StringUtils;

import db.ItemAttributeType;
import db.ItemType;
import db.TypeAttribute;
import util.DBUtil;
import view.DrawCatalog;

@WebServlet("/")
public class MainPageController extends BaseController {

    private static final long serialVersionUID = 1L;

    @Override
	protected void doOnGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException, SQLException {
			RequestDispatcher view = request.getRequestDispatcher("/main.jsp");
			request.setCharacterEncoding("UTF-8");
			
			int selectedCatalogId = 0;
			String catalogNr = request.getParameter("catalog");
			if (StringUtils.isNotBlank(catalogNr) && StringUtils.isNumeric(catalogNr)){	
				selectedCatalogId = Integer.parseInt(catalogNr.trim());
				DBUtil m = new DBUtil();
				ItemType catalog = m.getItemTypeById(selectedCatalogId);
				Set<ItemType> subCatalogs = catalog.getItemTypes();
				if(subCatalogs != null && subCatalogs.size() == 0){
				    request.setAttribute("lastCatalog", m.getItemTypeById(selectedCatalogId).getTypeName());
				    SearchForm form = new SearchForm();
				    ItemType item =  m.getItemTypeById(Integer.parseInt(catalogNr));
				    form.setType(item.getTypeName());
				    List<TypeAttribute> itemAttributes = m.getTypeAttributesByItemType(Integer.parseInt(catalogNr));
				    for (TypeAttribute attribute : itemAttributes) {
					AttributeModel attibute = new AttributeModel();
					ItemAttributeType attributeType = attribute.getItemAttributeType();
					attibute.setAttributeName(attributeType.getTypeName());
					form.getAttributes().put(attributeType.getItemAttributeType(), attibute);
				    }
				    request.setAttribute("form", form);
				}else{
				    request.setAttribute("form", new SearchForm());
				}				   					
			}else{
			    request.setAttribute("form", new SearchForm());
			}
			
			DrawCatalog drawCatalog = new DrawCatalog();
			String categoryTree = drawCatalog.DrawCatalogTree(selectedCatalogId);
			if(categoryTree != null){
				request.setAttribute("categoryTree", categoryTree);
			}		
			view.forward(request, response); 
	}

    @Override
    protected void doOnPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {

	request.getSession().invalidate();
	// String logoutPage = request.getParameter("/login.jsp");
	response.sendRedirect(request.getContextPath()+"/login");

    }

}
